import Vue from "vue";
import Vuex from "vuex";
import { login, logout, getInfo, phoneDecrypt } from "@/config/api.js";

Vue.use(Vuex); //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
  // 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
  state: {
    // token
    token: null,
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: uni.$u.trim(username), password: password })
          .then((response) => {
            uni.setStorageSync("loginTokens", response.token);
            commit("SET_TOKEN", response.token);
            resolve(response);
          })
          .catch((error) => {
            console.log("catch===>response", error);
            reject(error);
          });
      });
    },
    // 登出
    Logout({ commit, state }) {
      commit("SET_TOKEN", "");
      uni.removeStorageSync("loginTokens");
      uni.removeStorageSync("identify");

      // return new Promise((resolve) => {
      // 	logout().then(() => {
      // 		commit('SET_TOKEN', '')
      // 		uni.removeStorageSync('loginTokens')
      // 		uni.removeStorageSync('identify')
      // 		resolve()
      // 	}).catch(() => {
      // 		resolve()
      // 	})
      // })
    },
  },
  getters: {
    token: (state) => state.token,
  },
});
export default store;
